package com.apes.sms.systemSetting.model;

/**
 * Created by lishikun on 2021/12/16 14:57
 */

import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.scm.masterdata.party.model.PartyRole;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = ScopeBusiness.CONST_TABLE_NAME)
public class ScopeBusiness extends Model {
    public static final String CONST_TABLE_NAME = "sms_scope_business";
    @OneToMany(mappedBy = "scopeBusiness", cascade = CascadeType.ALL, orphanRemoval = true)
    List<BrandBusiness> brandBusinesses = new ArrayList<>();
    @OneToMany(mappedBy = "scopeBusiness", cascade = CascadeType.ALL, orphanRemoval = true)
    List<ClassifyBusiness> classifyBusinesses = new ArrayList<>();
    @Id
    @Column(name = "id", length = 4)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "经营范围表",padding = 4)
    @Comment("编码")
    private String id;
    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier_id", referencedColumnName = "id")
    @Comment("供应商")
    private PartyRole supplier;
    @Column(name = "install_supplier", nullable = false, columnDefinition = "number(2, 0) default 1")
    @Comment("装机供应商")
    private boolean installSupplier;

    public List<BrandBusiness> getBrandBusinesses() {
        String distinctBrand = "";
        for (BrandBusiness brandBusiness : brandBusinesses) {
            String carlabelId = brandBusiness.getMasCarBrand().getId();
            if (StringUtils.hasText(distinctBrand) && distinctBrand.indexOf(carlabelId) != -1) throw new RuntimeException("厂牌重复, 厂牌: " + carlabelId);
            distinctBrand += carlabelId + ";";
            brandBusiness.setScopeBusiness(this);
        }
        return brandBusinesses;
    }

    public List<ClassifyBusiness> getClassifyBusinesses() {
        String distinctClassify = "";
        for (ClassifyBusiness classifyBusiness : classifyBusinesses) {
            String classifyId = classifyBusiness.getClassify().getId();
            if (StringUtils.hasText(distinctClassify) && distinctClassify.indexOf(classifyId) != -1) throw new RuntimeException("品类重复, 品类: " + classifyId);
            distinctClassify += classifyId + ";";
            classifyBusiness.setScopeBusiness(this);
        }
        return classifyBusinesses;
    }
}
